package com.cafuc.jdk8;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class StreamAPi {
    public void streamTest(){

        //list创建流
        List<String> aa = new ArrayList<>();
        aa.add("ddd");
        aa.add("hhh");
        aa.add("xxx");
        aa.add("zzz");
        aa.stream().filter(item -> item.contains("h") || item.contains("d"))
                .sorted(((o1, o2) -> o1.compareTo(o2)))
                .forEach(item -> System.out.println(item));
        //数组创建流
        String[] array = new String[]{"abc", "efg","hij", "klm"};
        System.out.println(array);

        Arrays.stream(array).forEach( System.out::println);

        //值创建流
        Stream.of("aaa", "bbb", "ccc").forEach( System.out::println);

        //函数创建流
        Stream.iterate(0, i -> i + 2).limit(20).forEach(System.out::println);
        Stream.generate(new Random() :: nextInt).limit(10).forEach(System.out::println);

        List<Integer> list = Arrays.asList(1, 3, 5, 11, 7, 7, 8);
        List<Integer> list2 = list.stream()
                .distinct()
                .map(item -> item * 2)
                .filter(item -> item % 1 == 0)
                .sorted(Comparator.reverseOrder())
                .collect(Collectors.toList());
        System.out.println(list2);

        Integer[] arrays1 = list.stream()
                .distinct()
                .map(item -> item * 2)
                .filter(item -> item % 1 == 0)
                .sorted(Comparator.reverseOrder())
                .toArray(Integer[] ::new);
        System.out.println(arrays1);

        Map<String, String> map1 = new HashMap<>();
        map1.put("aaa", "fdjs");
        map1.put("bbb", "djnj");
        map1.put("ccc", "kufu");
        map1.put("ddd", "kufu");
        map1.put("eee", "djnj");
        map1.entrySet().stream()
                .sorted(Map.Entry.comparingByKey())
                .forEach(item -> System.out.println(item));
        Map<String, String> map2 = map1.entrySet().stream()
                .sorted(Map.Entry.comparingByKey())
                .collect(
                        Collectors.toMap(
                                Map.Entry :: getKey,
                                Map.Entry :: getValue,
                                (oldValue, newValue) -> oldValue,
                                LinkedHashMap :: new
                ));
        System.out.println(map2);
        String keys = map1.entrySet().stream()
                .sorted(Map.Entry.comparingByKey())
                .map(item -> item.getKey())
                .collect(Collectors.joining());
        System.out.println(keys);

    }

    public static void main(String[] args) {
        StreamAPi streamAPi = new StreamAPi();
        streamAPi.streamTest();
    }
}
